package cn.openea.perpartner.meily.scheduledtasks.logistics;

import cn.openea.perpartner.common.core.utils.SpringContextUtils;
import cn.openea.perpartner.meily.constant.CommonConstants;
import cn.openea.perpartner.meily.eventlistener.event.SyncLogisticsEvent;
import cn.openea.perpartner.meily.web.entity.LogisticsInfo;
import cn.openea.perpartner.meily.web.service.logistics.LogisticsQuery;
import cn.openea.perpartner.meily.web.service.logistics.businessModule.LogisticsModlueHandler;
import cn.openea.perpartner.meily.web.service.logistics.businessModule.LogisticsModuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 物流定时更新
 * @createTime 2023年05月11日 20:21:00
 */
@Slf4j
@Component
public class SyncLogisticsTask {

    @Resource
    private LogisticsQuery logisticsQuery;
    @Resource
    private LogisticsModlueHandler logisticsModlueHandler;

    /**
     * 同步实时物流
     * 4小时执行一次
     */
    @Scheduled(cron = "0 0 0/4 * * ?")
    public void realTimeLogisticsSyncService() {
        log.info("realTime logistics sync task start execution");
        List<LogisticsInfo> transportLogisticsList = logisticsQuery.findInTransportLogisticsList();
        if (transportLogisticsList.isEmpty()) {
            return;
        }
        for (LogisticsInfo logisticsInfo : transportLogisticsList) {
            try {
                SpringContextUtils.getApplicationContext().publishEvent(new SyncLogisticsEvent(this, logisticsInfo));
            } catch (Exception e) {
                log.error("实时物流同步失败，失败原因：{}，物流编号：{}", e.getMessage(), logisticsInfo.getId());
            }
        }
    }

    /**
     * 同步业务状态
     * 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void logisticsSyncBusinessStatus() {
        log.info("logistics sync business status start execution");
        // 获取到没有业务状态未完成的数据
        List<LogisticsInfo> logisticsInfoList = logisticsQuery.findInLogisticsListBycBusinessStatus(CommonConstants.LOGISTICS.BUSINESS_UNFINISHED);
        if (logisticsInfoList.isEmpty()) {
            return;
        }
        for (LogisticsInfo logisticsInfo : logisticsInfoList) {
            try {
                LogisticsModuleService service = logisticsModlueHandler.getService(logisticsInfo.getModule());
                service.businessStatusSync(logisticsInfo);
            } catch (Exception e) {
                log.error("物流业务状态同步失败，失败原因：{} 失败模块：{} 失败编号：{}", e.getMessage(), logisticsInfo.getModule(), logisticsInfo.getModuleId());
            }

        }
    }
}
